package cn.easy.kitchen.service;

import cn.easy.base.bean.PageBean;
import cn.easy.base.service.BaseService;
import cn.easy.kitchen.domain.Customer;
import cn.easy.kitchen.repository.CustomerDao;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Component
public class CustomerService extends BaseService<Customer> {
    @Autowired
    private CustomerDao	customerDao;

    public Page<Customer> search(Map<String, Object> searchParams, PageBean pageBean) {
        return customerDao.findAll(spec(searchParams), pageBean.toPageRequest(new Sort(Direction.DESC, "createdAt")));
    }

    public List<Customer> search(Map<String, Object> searchParams, Sort... sort) {
        return customerDao.findAll(spec(searchParams), sort == null || sort.length == 0  ? new Sort(Direction.DESC, "createdAt") : sort[0]);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public void delete(String id) {
        customerDao.delete(id);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public void deleteAll() {
        customerDao.deleteAll();
    }

    public Customer getOne(String id) {
        if (StringUtils.isBlank(id)) {
            return null;
        }
        return customerDao.findOne(id);
    }

    public List<Customer> findAll(List<String> idList) {
        return Lists.newArrayList(customerDao.findAll(idList));
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public Customer save(Customer customer) {
        return customerDao.save(customer);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public void save(List<Customer> customerList) {
        customerDao.save(customerList);
    }

    public Customer findByOldNo(String code) {
        if (StringUtils.isBlank(code)) {
            return null;
        }
        return customerDao.findByOldNo(code);
    }

    public Customer findByShortName(String shortName) {
        if (StringUtils.isBlank(shortName)) {
            return null;
        }
        List<Customer> customers = customerDao.findByShortName(shortName);
        return customers.isEmpty() ? null : customers.get(0);
    }

    /**
     * 统计学校数量
     * @return
     */
    public int countSchool(){
        return customerDao.countSchool();
    }
}


